<template>
	<view class="container">
		<view class="header">
			<view class="p10">
				<u--input prefixIcon="search" placeholder="请输入门店名称" border="none" shape="circle"
					:customStyle="{background:'#f5f5f5',height:'60rpx',paddingLeft:'20rpx'}" v-model="formInline.name"
					@input="toSearch">
				</u--input>
			</view>
		</view>
		<view class="" v-if="tableData.length != 0">
			<view class="card c3 mb10 cshow" v-for="(item,index) in tableData" :key="item.id">
				<view style="display: flex;justify-content: space-between;align-items: center;">
					<view class="f18 wei6">#{{item.id}}</view>
					<view style="display: flex;align-items: center;">
						<uni-icons type="phone" size="25"></uni-icons>
						<view class="wei f14">{{item.phone}}</view>
					</view>
				</view>
				<u-divider></u-divider>
				<view class="item_container">
					<view class="item">连锁名称：{{item.name}}</view>
					<view class="item">OEM：{{item.oem_name}}</view>
					<view class="item">代理：{{item.agent_name}}</view>
					<view class="item">合伙人：{{item.partner_name}}</view>
					<view class="stutas"><span>状态：</span>
						<u-tag v-if="item.status == 0" type="success" text="正常" size="mini" plain class="tag"></u-tag>
						<u-tag v-if="item.status == 1" type="warning" text="禁用" size="mini" plain class="tag"></u-tag>
					</view>
				</view>
				<u-divider></u-divider>
				<view class="footer">
					<view class="footer_item" @click="edit(item)"
						v-if="menus.includes('chain_stores/chainStores/edit')">编辑</view>
					<view class="footer_item" @click="qiAndJin(item, 0)"
						v-if="menus.includes('chain_stores/chainStores/setChainStoresrStatus') && item.status == 1">启用
					</view>
					<view class="footer_item" @click="qiAndJin(item, 1)"
						v-if="menus.includes('chain_stores/chainStores/setChainStoresrStatus') && item.status == 0">禁用
					</view>
				</view>
			</view>
			<view class="" style="width: 100%;height: 140rpx;"></view>
		</view>
		<view v-if="tableData.length==0" class="np f-c-c">
			<view class="iconfont icon-queshengtu cb" style="font-size: 90rpx;"></view>
			<view class="f12 cb mt20">暂无门店</view>
		</view>
		<view class="navbar2 bt f-row">
			<view class="f-c" style="width: 168rpx;background: #FBFBFB;">门店设置</view>
			<view class="f-1 f-row bf">
				<template v-for="(v, i) in navs">
					<view class="f-1 f-y-c" @click="djTab(v)" :key="i" v-if="menus.includes(v.role)">
						<view class="wh f-c f-y-c">
							<text class="cf7c mr10" :style="{ color: subColor ,fontSize:'38rpx'}"
								:class="['icon' + v.i, 'iconfont f20']"></text>
							<view class="">{{ v.t }}</view>
						</view>
					</view>
				</template>
			</view>
		</view>
		<u-popup :show="chainShow" @close="chainShow = false" mode="center" :round="10" :safeAreaInsetBottom="false">
			<view class="popup">
				<u--form :model="ruleForm" ref="ruleFormRef" labelWidth="70" :rules="rules">
					<u-form-item label="合伙人" prop="partner_id" v-if="adminInfo.type == 3">
						<uni-data-select v-model="ruleForm.partner_id" :localdata="partner_idList" disabled
							:clear="false"></uni-data-select>
					</u-form-item>
					<u-form-item label="连锁名称" prop="name" ref="item1">
						<u--input placeholder="请输入内容" border="surround" v-model="ruleForm.name"></u--input>
					</u-form-item>
					<u-form-item label="手机号 " prop="phone" ref="item1">
						<u--input placeholder="请输入内容" border="surround" v-model="ruleForm.phone"></u--input>
					</u-form-item>
					<u-form-item label="商品上传数量" v-if="menus.includes('store/store/productNumber')">
						<u--input placeholder="请输入内容" border="surround" v-model="ruleForm.upload_product_number"
							type="number"></u--input>
					</u-form-item>
					<u-form-item label="LOGO" ref="item1" label-width="50">
						<u-upload :fileList="ruleForm.logo_img" @afterRead="afterRead" @delete="deletePic" name="1"
							multiple :maxCount="3"></u-upload>
					</u-form-item>
					<u-form-item label="营业执照" ref="item1" label-width="50">
						<u-upload :fileList="ruleForm.bus_img" @afterRead="afterRead" @delete="deletePic" name="2"
							multiple :maxCount="3"></u-upload>
					</u-form-item>
				</u--form>
				<u-button text="确定" type='primary' @click="submit"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import COS from 'cos-wx-sdk-v5';
	import CryptoJS from 'crypto-js';
	import site from '@/custom/siteroot.js';
	import {
		mapState,
	} from 'vuex'
	export default {
		data() {
			return {
				formInline: {
					page: 1,
					limit: 10,
					name: '',
					phone: ''
				},
				tableData: [],
				chainShow: false,
				ruleForm: {
					agent_id: '',
					partner_id: "",
					name: '',
					upload_product_number: 0,
					logo_img: [],
					bus_img: [],
					phone: '',
				},
				cos: null, // COS SDK 实例
				rules: {
					name: [{
						required: true,
						message: '请填写',
						trigger: 'blur'
					}],
					phone: [{
							required: true,
							message: '请填写',
							trigger: 'blur'
						},
						{
							min: 11,
							max: 11,
							message: '手机格式不正确',
							trigger: 'blur'
						},
					],
				},
				navs: [{
					i: '-jiahao',
					k: 'xjsp',
					url: 'xzlx',
					t: '新建门店',
					role: 'chain_stores/chainStores/add'
				}],
				addAndEditStatus: 0,
				subColor: uni.getStorageSync("subject_color"),
				adminInfo: uni.getStorageSync("adminInfo"),
				partner_idList: [],
				hasLoadedData: false
			}
		},
		onReady() {
			this.$refs.ruleFormRef.setRules(this.rules)
		},
		mounted() {
			// 初始化 COS SDK
			this.initCOS();
		},
		computed: {
			...mapState({
				menus: state => state.menus,
			}),
		},
		methods: {
			toSearch() {
				this.hasLoadedData = false;
				this.getList()
			},
			getList() {
				uni.showLoading()
				this.beg.request({
					url: '/admin/chain_stores.ChainStores/index',
					method: 'get',
					data: this.formInline
				}).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						res.data.data.forEach(v => {
							try {
								v.bus_img = JSON.parse(v.bus_img);
								v.bus_img = v.bus_img.map(item => ({
									url: site.siteimgroot + item,
									src: item
								}));
								v.logo_img = JSON.parse(v.logo_img);
								v.logo_img = v.logo_img.map(item => ({
									url: site.siteimgroot + item,
									src: item
								}));
							} catch (e) {
								console.error('JSON parsing error', e);
							}
						});
						let newData = res.data.data
						if (!this.hasLoadedData) {
							this.tableData = newData;
							this.hasLoadedData = true;
							this.null2str(this.tableData);
						} else {
							this.tableData = this.tableData.concat(newData);
							this.null2str(this.tableData);
						}
					}
				}).catch(error => {
					console.error('请求失败', error);
				});
			},
			null2str(data) {
				data.forEach(item => {
					Object.keys(item).forEach(key => {
						if (item[key] === null) {
							item[key] = "-";
						}
					});
				});
				return data;
			},
			getPartnerList() {
				this.beg.request({
						url: '/admin/select/get_select_data',
						data: {
							agent_id: this.adminInfo.agent_id,
							type: 3
						}
					})
					.then((res) => {
						if (res.code == 1) {
							var classfiy = []
							res.data.forEach(i => {
								classfiy.push({
									text: i.label
								})
							})
							this.partner_idList = classfiy;
							if (this.adminInfo.type == 3) {
								ruleForm.partner_id = this.adminInfo.partner_id;
							}

						} else {
							uni.$u.toast(res.msg)
						}
					})
					.catch()
			},
			edit(val) {
				this.ruleForm = val
				this.chainShow = true
				this.addAndEditStatus = 0
			},
			initCOS() {
				this.beg.request({
					url: '/admin/Cos/refreshToken',
					method: 'get',
				}).then(res => {
					// 获取临时密钥
					const {
						tmpSecretId,
						tmpSecretKey,
						sessionToken,
						startTime,
						expiredTime
					} = res.data;
					this.cos = new COS({
						getAuthorization: (options, callback) => {
							callback({
								TmpSecretId: tmpSecretId,
								TmpSecretKey: tmpSecretKey,
								SecurityToken: sessionToken,
								StartTime: startTime,
								ExpiredTime: expiredTime,
							});
						},
					});
				}).catch(error => {
					console.error('获取临时密钥失败:', error);
				});
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				if (event.name == '1') {
					let fileListLen = this.ruleForm.logo_img.length
					lists.map((item) => {
						this.ruleForm.logo_img.push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const result = await this.handleFileInUploading(lists[i])
						let item = this.ruleForm.logo_img[fileListLen]
						this.ruleForm.logo_img.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result.headers.location,
							src: result.Location,
						}))
						fileListLen++;
					}
				} else if (event.name == '2') {
					let fileListLen = this.ruleForm.bus_img.length
					lists.map((item) => {
						this.ruleForm.bus_img.push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const result = await this.handleFileInUploading(lists[i])
						let item = this.ruleForm.bus_img[fileListLen]
						this.ruleForm.bus_img.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result.headers.location,
							src: result.Location,
						}))
						fileListLen++;
					}
				}
			},
			handleFileInUploading(event) {
				return new Promise((resolve, reject) => {
					const that = this
					const filePath = event.url
					const str = filePath.substr(filePath.lastIndexOf('/') + 1)
					const sha1Hash = CryptoJS.SHA1(str).toString();
					const fileName = '/storage/default/' + this.getCurrentDate() + '/' + str
					that.cos.uploadFile({
						Bucket: 'douyin-1325951894',
						Region: 'ap-beijing',
						Key: fileName,
						FilePath: filePath,
						SliceSize: 1024 * 1024 * 5,
						onFileFinish: function(err, data, options) {
							const fileUrl = '/' + options.Key
							that.beg.request({
								url: '/admin/Cos/callback',
								method: 'POST',
								data: {
									url: fileUrl,
									name: fileName,
									size: event.size,
									type: event.type,
									sha1: sha1Hash,
								},
							}).then(res => {
								if (res.code == 1) {
									setTimeout(() => {
										resolve(data)
									}, 500)
								}
							})
						},
					}, function(err, data, options) {
						// console.log(data,options)
					});
				})
			},
			deletePic(event) {
				if (event.name == '1') {
					this.ruleForm.logo_img.splice(event.index, 1)
				} else if (event.name == '2') {
					this.ruleForm.bus_img.splice(event.index, 1)
				}
			},
			getCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = (now.getMonth() + 1).toString().padStart(2, '0');
				const day = now.getDate().toString().padStart(2, '0');
				return year.toString() + month + day;
			},
			djTab() {
				this.ruleForm.agent_id = ''
				this.ruleForm.partner_id = ''
				this.ruleForm.name = ''
				this.ruleForm.upload_product_number = 0
				this.ruleForm.logo_img = []
				this.ruleForm.bus_img = []
				this.ruleForm.phone = ''
				this.chainShow = true
				this.addAndEditStatus = 1
			},
			qiAndJin(val, status) {
				let name = ''
				if (status == 0) {
					name = '启用'
				} else if (status == 1) {
					name = '禁用'
				}
				uni.showModal({
					title: '温馨提示',
					content: `确定${name}该合伙人？`,
					success: (res) => {
						if (res.confirm) {
							this.beg.request({
								url: '/admin/chain_stores.ChainStores/setChainStoresrStatus',
								method: 'post',
								data: {
									id: val.id,
									status: status,
								}
							}).then(res => {
								if (res.code == 1) {
									uni.$u.toast(res.msg)
									setTimeout(res => {
										this.hasLoadedData = false;
										this.formInline.page = 1;
										this.getList()
									}, 800)

								} else {
									uni.$u.toast(res.msg)
								}
							})
						}
					}
				})
			},
			submit() {
				this.$refs.ruleFormRef.validate().then(res => {
					const logoSrcs = [];
					this.ruleForm.logo_img.forEach((item) => {
						const exists = item.src.includes('douyin');
						if (exists) {
							const afterCom = item.src.substring(item.src.lastIndexOf('.com') + 4);
							logoSrcs.push(afterCom)
						} else {
							logoSrcs.push(item.src);
						}
					});
					this.ruleForm.logo_img = logoSrcs;
					const logoSrcs2 = [];
					this.ruleForm.bus_img.forEach((item) => {
						const exists = item.src.includes('douyin');
						if (exists) {
							const afterCom = item.src.substring(item.src.lastIndexOf('.com') + 4);
							logoSrcs2.push(afterCom)
						} else {
							logoSrcs2.push(item.src);
						}
					});
					this.ruleForm.bus_img = logoSrcs2;
					if (this.addAndEditStatus == 0) {
						this.beg.request({
							url: '/admin/chain_stores.ChainStores/edit',
							method: 'post',
							data: this.ruleForm
						}).then(res => {
							if (res.code == 1) {
								uni.$u.toast(res.msg)
								this.chainShow = false
								setTimeout(res => {
									this.hasLoadedData = false;
									this.formInline.page = 1
									this.getList()
								}, 800)
							} else {
								uni.$u.toast(res.msg)
								this.chainShow = false
							}
						})
					} else {
						this.beg.request({
							url: '/admin/chain_stores.ChainStores/add',
							method: 'post',
							data: this.ruleForm
						}).then(res => {
							if (res.code == 1) {
								uni.$u.toast(res.msg)
								this.chainShow = false
								setTimeout(res => {
									this.hasLoadedData = false;
									this.formInline.page = 1
									this.getList()
								}, 800)
							} else {
								uni.$u.toast(res.msg)
								this.chainShow = false
							}
						})
					}

				}).catch(errors => {})
			},
		},
		onLoad() {
			this.getList()
			this.getPartnerList()
		},
		onReachBottom() {
			this.formInline.page++
			this.getList()
		}
	}
</script>

<style lang="scss" scoped>
	.header {
		background-color: #fff;
	}

	::v-deep .uni-forms-item {
		align-items: center;
	}

	.card {
		width: 94%;
		margin: 0 auto;
		margin-top: 38rpx;
	}

	.item_container {
		.item {
			font-size: 29rpx;
			font-weight: 500;
			color: #000;
			margin-top: 15rpx;
		}

		.stutas {
			display: flex;
			align-items: center;
			margin-top: 15rpx;
		}
	}

	.footer {
		display: flex;
		justify-content: flex-start;
		align-items: center;

		.footer_item {
			width: 125rpx;
			height: 55rpx;
			border-radius: 8rpx;
			background-color: #fdda34;
			color: #000;
			font-weight: 600;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.footer_item:not(:first-child) {
			margin-left: 30rpx;
		}
	}

	.popup {
		width: 90vw;
		padding: 40rpx 20rpx;
	}

	.navbar2 {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		background: #fff;
		box-shadow: 0 0rpx 8rpx 4rpx rgba(0, 0, 0, 0.05);
	}
</style>